<style>
	.mybtn{
		color: aliceblue;
		border-radius:5px;
		background-color: rgba(0, 127, 203, 1.0);
		border: 1px solid rgb(0, 145, 214);
	}  
</style>
<div>
    <button onclick="startAudio()" class="mybtn">开始语音</button>
    <button onclick="stopAudio()" class="mybtn">停止语音</button>
    <div id="msgdiv"></div>
</div>
<script>
    var audioFile = null;//录音的二进制数据
    var mediaRecorder = null;
    function startAudio(){
        navigator.mediaDevices.getUserMedia({ audio: true })
        .then(function(stream) {
            const options = {
                duration: 5000,//指定录音的时长，单位 ms
                sampleRate: 16000,//采样率
                numberOfChannels: 1,//录音通道数
                encodeBitRate: 96000,//编码码率
                format: 'pcm',//音频格式
            }
            mediaRecorder = new MediaRecorder(stream,options);
            mediaRecorder.start();

            // 录音结束时，停止并下载录音文件
            mediaRecorder.addEventListener("dataavailable", function(event) {
                audioFile = new Blob([event.data], { type: "audio/wav" });
            });

            // 录音时间到达指定时长时，自动停止录音
            setTimeout(function() {
                mediaRecorder.stop();
                setTimeout(function(){
                    sendAudio();
                },1000)
            }, 5000);
        })
        .catch(function(error) {
            console.error(error);
        });
    }

    function stopAudio(){
        try{
            mediaRecorder.stop()
        }catch(e){
        }
    }
    
function sendAudio(){
    var formdata = new FormData();
    formdata.append("record", audioFile);
    console.log(formdata);
    $.ajax({
        url: "ai",
        type: 'post',
        processData: false,
        contentType: false,
        data: formdata,
        dataType: 'json',
        success: function (data) {
            let res = data.filename;
            document.getElementById("msgdiv").innerHTML = res
            if(res.indexOf("退出")>=0){
              
            }else if(res.indexOf("查询")>=0){
                location.href = "querypagemsg?vf=1"
            }else if(res.indexOf("首页")>=0){
                location.href = "/?vf=1"
            }else if(res.indexOf("停止语音")>=0){
                stopAudio()
                return;
            }else if (res.indexOf("识别")>=0){
                location.href = "identify?vf=1"
            }else if(res.indexOf("个人")>=0){
				  location.href = "userCenter?vf=1"
			}else if(res.indexOf("中心")>=0){
				  location.href = "userCenter?vf=1"
			}else if(res.indexOf("圈友")>=0){
				  location.href = "user_com?vf=1"
			}else if(res.indexOf("交流")>=0){
				  location.href = "user_com?vf=1"
			}
            startAudio()
        }
    });
}
//是否开启语音方法的自动调用
{% if request.values.get('vf','')=='1' %}
    startAudio()
{% endif %}
</script>